package cn.leftsite.juc.producerandconsumer;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author wangjinqiang
 * @date 2019-06-06
 */
public class Consumer implements Runnable {
    private final BlockingQueue<PCData> queue;
    public static final int SLEEPTIME = 1000;

    public Consumer(BlockingQueue<PCData> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        System.out.println("start Consumer id="+Thread.currentThread().getId() );
        Random r = new Random();

        try {
            while (true){
                // 提取任务
                PCData data = queue.poll(2, TimeUnit.SECONDS);
                if (null != data) {
                    //  计算平方
                    int re = data.getIntData() * data.getIntData();
                    System.out.println(String.format("%s*%s=%s", data.getIntData(), data.getIntData(), re));
                    Thread.sleep(r.nextInt(SLEEPTIME));
                }else {
                    System.out.println("poll timeout, exit");
                    break;
                }
            }
        }catch (InterruptedException e){
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }


}
